<?php

namespace app\controller;

use app\BaseController;
use app\model\TowerCraneNdata;
use app\model\TowerCraneRdata;
use think\facade\Cache;
use think\facade\Db;

/*
创建（Create）、更新（Update）、读取（Retrieve）和删除（Delete）
 */
class CacheController extends BaseController
{
    public function getCacheData()
    {
        $towerData = Cache::get('tower_crane_rdata');
        if (!$towerData) {
            $towerData = DB::table('tower_crane_rdata')->select();
            Cache::set('tower_crane_rdata', $towerData, 20);
            return success('set cache');
        } else {
            $data[] = 'read cache';
            $data[] = $towerData;
            return success($data);
        }
    }
    public function createCacheData()
    {
        // Cache::store('redis')->set('name','value',10);
        // $cache = Cache::store('redis')->get('name');
        // return success($cache);
        // die;
        $request = $this->request->param();
        $cache = Cache::get('tower'); //数据
        if ($cache) {
            $inc = Cache::inc('inc'); //数据
            $request['inc'] = Cache::get('inc');
            $json_request = json_encode($request);
            Cache::push('tower', $json_request);
        } else {
            $inc = Cache::set('inc', 1); //数据
            $request['inc'] = Cache::get('inc');
            $json_request = json_encode($request);
            Cache::set('tower', [$json_request]);
        }
        $list['inc'] = $request['inc'];
        $list['list'] = Cache::get('tower');
        if ($inc > 9) {
            $TowerCraneRdata = new TowerCraneRdata;
            foreach ($list['list'] as $key => $value) {
                $value = json_decode($value, true);
                unset($value['inc']);
                $insert[] = $value;
                TowerCraneNdata::update($value, ['eid' => $value['eid']]);
            }
            $TowerCraneRdata->saveAll($insert);
            Cache::delete('inc');
            Cache::delete('tower');
        }

        return success($list);
    }
    public function clear()
    {
        $a = Cache::clear();
        return success($a);
    }
}
